import { apiInterceptors, createMenu, deleteMenu, getMenuTree, updateMenu } from '@/client/api';
import { Button, Form, Input, InputNumber, Modal, Select, Space, Table, Tag, message } from 'antd';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import type { MenuInfo, MenuRequest } from '@/client/api/auth';

const MenuManagement = () => {
  const { t } = useTranslation();
  const [menus, setMenus] = useState<MenuInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingMenu, setEditingMenu] = useState<MenuInfo | null>(null);
  const [form] = Form.useForm();

  // 扁平化菜单树
  const flattenMenus = (menus: MenuInfo[]): MenuInfo[] => {
    let result: MenuInfo[] = [];
    menus.forEach(menu => {
      result.push(menu);
      if (menu.children && menu.children.length > 0) {
        result = result.concat(flattenMenus(menu.children));
      }
    });
    return result;
  };

  // 加载菜单树
  const loadMenuTree = async () => {
    setLoading(true);
    try {
      const [, data] = await apiInterceptors(getMenuTree());
      console.log('Menu management - API response:', data);
      
      // 后端返回格式: Result.succ(menus) -> data就是菜单数组
      if (data && Array.isArray(data)) {
        console.log('Menu management - menus count:', data.length);
        setMenus(data);
      } else {
        console.warn('Menu management - invalid data format:', data);
        message.warning('数据格式不正确');
        setMenus([]);
      }
    } catch (error) {
      console.error('Load menu tree failed:', error);
      message.error('加载失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadMenuTree();
  }, []);

  // 获取父菜单选项
  const getParentMenuOptions = () => {
    const allMenus = flattenMenus(menus);
    return [
      { label: t('root_menu') || '根菜单', value: 0 },
      ...allMenus
        .filter(m => m.menu_type !== 3) // 按钮不能作为父菜单
        .map(m => ({
          label: m.menu_name,
          value: m.id,
        })),
    ];
  };

  // 打开新增/编辑弹窗
  const handleAdd = (parentId?: number) => {
    setEditingMenu(null);
    form.resetFields();
    if (parentId !== undefined) {
      form.setFieldValue('parent_id', parentId);
    }
    setModalVisible(true);
  };

  const handleEdit = (record: MenuInfo) => {
    setEditingMenu(record);
    form.setFieldsValue({
      parent_id: record.parent_id,
      menu_code: record.menu_code,
      menu_name: record.menu_name,
      menu_name_en: record.menu_name_en,
      menu_type: record.menu_type,
      route_path: record.route_path,
      component_path: record.component_path,
      icon: record.icon,
      sort_order: record.sort_order,
      permission_code: record.permission_code,
      status: record.status,
      is_visible: record.is_visible,
      remark: record.remark,
    });
    setModalVisible(true);
  };

  // 删除菜单
  const handleDelete = (record: MenuInfo) => {
    if (record.children && record.children.length > 0) {
      message.warning(t('delete_menu_with_children_warning') || '请先删除子菜单');
      return;
    }

    Modal.confirm({
      title: t('confirm_delete') || '确认删除',
      content: `${t('confirm_delete_menu') || '确定要删除菜单'} "${record.menu_name}" ${t('question_mark') || '吗？'}`,
      okText: t('confirm') || '确定',
      cancelText: t('cancel') || '取消',
      onOk: async () => {
        try {
          const [error] = await apiInterceptors(deleteMenu(record.id));
          if (!error) {
            message.success(t('delete_success') || '删除成功');
            loadMenuTree();
          }
        } catch (error) {
          message.error(t('delete_failed') || '删除失败');
        }
      },
    });
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const menuData: MenuRequest = {
        ...values,
        id: editingMenu?.id,
      };

      if (editingMenu) {
        // 更新菜单
        const [error] = await apiInterceptors(updateMenu(editingMenu.id, menuData));
        if (!error) {
          message.success(t('update_success') || '更新成功');
          setModalVisible(false);
          loadMenuTree();
        }
      } else {
        // 新增菜单
        const [error] = await apiInterceptors(createMenu(menuData));
        if (!error) {
          message.success(t('create_success') || '创建成功');
          setModalVisible(false);
          loadMenuTree();
        }
      }
    } catch (error) {
      console.error('Form validation failed:', error);
    }
  };

  const menuTypeMap: Record<number, string> = {
    1: t('directory') || '目录',
    2: '菜单',
    3: t('button') || '按钮',
  };

  const columns = [
    {
      title: t('menu_name') || '菜单名称',
      dataIndex: 'menu_name',
      key: 'menu_name',
      width: 200,
    },
    {
      title: t('menu_code') || '菜单编码',
      dataIndex: 'menu_code',
      key: 'menu_code',
      width: 150,
    },
    {
      title: t('menu_type') || '类型',
      dataIndex: 'menu_type',
      key: 'menu_type',
      width: 100,
      render: (type: number) => <Tag color="blue">{menuTypeMap[type]}</Tag>,
    },
    {
      title: '图标',
      dataIndex: 'icon',
      key: 'icon',
      width: 100,
    },
    {
      title: t('sort_order') || '排序',
      dataIndex: 'sort_order',
      key: 'sort_order',
      width: 80,
    },
    {
      title: t('route_path') || '路由路径',
      dataIndex: 'route_path',
      key: 'route_path',
      width: 200,
    },
    {
      title: t('permission_code') || '权限编码',
      dataIndex: 'permission_code',
      key: 'permission_code',
      width: 150,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: (status: number) => (
        <Tag color={status === 1 ? 'green' : 'red'}>{status === 1 ? t('active') || '启用' : t('disabled') || '禁用'}</Tag>
      ),
    },
    {
      title: t('visible') || '可见',
      dataIndex: 'is_visible',
      key: 'is_visible',
      width: 80,
      render: (visible: number) => (
        <Tag color={visible === 1 ? 'green' : 'red'}>{visible === 1 ? t('yes') || '是' : t('no') || '否'}</Tag>
      ),
    },
    {
      title: t('action') || '操作',
      key: 'action',
      fixed: 'right' as const,
      width: 200,
      render: (_: any, record: MenuInfo) => (
        <Space>
          <Button type="link" size="small" onClick={() => handleAdd(record.id)}>
            {t('add_sub') || '添加子菜单'}
          </Button>
          <Button type="link" size="small" onClick={() => handleEdit(record)}>
            编辑
          </Button>
          <Button type="link" size="small" danger onClick={() => handleDelete(record)}>
            删除
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ padding: 24 }}>
      <div style={{ marginBottom: 16 }}>
        <Button type="primary" onClick={() => handleAdd()}>
          {t('add_menu') || '新增菜单'}
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={menus}
        rowKey="id"
        loading={loading}
        pagination={false}
        scroll={{ x: 1500 }}
        expandable={{
          defaultExpandAllRows: true,
        }}
      />

      <Modal
        title={editingMenu ? t('edit_menu') || '编辑菜单' : t('add_menu') || '新增菜单'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => setModalVisible(false)}
        width={700}
        okText={t('confirm') || '确定'}
        cancelText={t('cancel') || '取消'}
      >
        <Form form={form} layout="vertical" style={{ marginTop: 20 }}>
          <Form.Item label={t('parent_menu') || '父级菜单'} name="parent_id" initialValue={0}>
            <Select options={getParentMenuOptions()} placeholder={t('please_select_parent_menu') || '请选择父级菜单'} />
          </Form.Item>

          <Form.Item
            label={t('menu_type') || '菜单类型'}
            name="menu_type"
            rules={[{ required: true, message: t('please_select_menu_type') || '请选择菜单类型' }]}
            initialValue={2}
          >
            <Select>
              <Select.Option value={1}>{t('directory') || '目录'}</Select.Option>
              <Select.Option value={2}>菜单</Select.Option>
              <Select.Option value={3}>{t('button') || '按钮'}</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item
            label={t('menu_code') || '菜单编码'}
            name="menu_code"
            rules={[
              { required: true, message: t('please_input_menu_code') || '请输入菜单编码' },
              { min: 2, max: 50, message: t('menu_code_length_error') || '菜单编码长度2-50个字符' },
            ]}
          >
            <Input placeholder={t('please_input_menu_code') || '请输入菜单编码'} />
          </Form.Item>

          <Form.Item
            label={t('menu_name') || '菜单名称'}
            name="menu_name"
            rules={[
              { required: true, message: t('please_input_menu_name') || '请输入菜单名称' },
              { min: 2, max: 100, message: t('menu_name_length_error') || '菜单名称长度2-100个字符' },
            ]}
          >
            <Input placeholder={t('please_input_menu_name') || '请输入菜单名称'} />
          </Form.Item>

          <Form.Item label={t('menu_name_en') || '英文名称'} name="menu_name_en">
            <Input placeholder={t('please_input_menu_name_en') || '请输入英文名称'} />
          </Form.Item>

          <Form.Item label={t('route_path') || '路由路径'} name="route_path">
            <Input placeholder={t('please_input_route_path') || '请输入路由路径，如：/admin/user'} />
          </Form.Item>

          <Form.Item label={t('component_path') || '组件路径'} name="component_path">
            <Input placeholder={t('please_input_component_path') || '请输入组件路径，如：pages/admin/user.tsx'} />
          </Form.Item>

          <Form.Item label="图标" name="icon">
            <Input placeholder={t('please_input_icon') || '请输入图标名称,如:UserOutlined'} />
          </Form.Item>

          <Form.Item label={t('permission_code') || '权限编码'} name="permission_code">
            <Input placeholder={t('please_input_permission_code') || '请输入权限编码，如：user:view'} />
          </Form.Item>

          <Form.Item label={t('sort_order') || '排序'} name="sort_order" initialValue={0}>
            <InputNumber min={0} style={{ width: '100%' }} placeholder={t('please_input_sort_order') || '请输入排序值'} />
          </Form.Item>

          <Form.Item label="状态" name="status" initialValue={1}>
            <Select>
              <Select.Option value={1}>{t('active') || '启用'}</Select.Option>
              <Select.Option value={0}>{t('disabled') || '禁用'}</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item label={t('visible') || '是否可见'} name="is_visible" initialValue={1}>
            <Select>
              <Select.Option value={1}>{t('yes') || '是'}</Select.Option>
              <Select.Option value={0}>{t('no') || '否'}</Select.Option>
            </Select>
          </Form.Item>

          <Form.Item label="备注" name="remark">
            <Input.TextArea rows={2} placeholder={t('please_input_remark') || '请输入备注'} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default MenuManagement;
